﻿#include <iostream>

class Stack {
private:
    int* data;
    //动态分配内存来储存栈中的元素
    int top;
    int capacity;
    //data数组可容纳的元素数量

public:
    // 构造函数，初始化栈
    Stack(int size) {
        capacity = size;
        data = new int[capacity];
        //使用new关键字动态分配内存，创建一个大小为capacity的整数数组
        //将数组的首地址存储在data指针中
        top = -1;
    }

    // 析构函数，释放内存
    ~Stack() {
        delete[] data;
    }

    // 判断栈是否为空
    bool isEmpty() {
        return top == -1;
    }

    // 判断栈是否已满
    bool isFull() {
        return top == capacity - 1;
    }

    // 数据进栈操作
    void push(int element) {
        if (!isFull()) {
            top++;
            data[top] = element;
        }
        else {
            std::cout << "Stack is full. Cannot push element." << std::endl;
        }
    }

    // 数据出栈操作
    int pop() {
        if (!isEmpty()) {
            int element = data[top];
            top--;
            return element;
        }
        else {
            std::cout << "Stack is empty. Cannot pop element." << std::endl;
            return -1;
        }
    }

    // 获取当前栈的大小
    int size() {
        return top + 1;
    }
};

int main() {
    int stackSize;
    std::cout << "请输入栈的大小: ";
    std::cin >> stackSize;
    Stack stack(stackSize);

    int choice;
    int element;
    do {
        std::cout << "1. 入栈\n2. 出栈\n3. 查看栈大小\n4. 检查栈是否为空\n5. 退出\n请选择操作: ";
        std::cin >> choice;
        switch (choice) {
        case 1:
            std::cout << "请输入要入栈的元素: ";
            std::cin >> element;
            stack.push(element);
            break;
        case 2:
            element = stack.pop();
            if (element != -1) {
                std::cout << "出栈元素: " << element << std::endl;
            }
            break;
        case 3:
            std::cout << "栈大小: " << stack.size() << std::endl;
            break;
        case 4:
            std::cout << "栈是否为空: " << (stack.isEmpty() ? "是" : "否") << std::endl;
            break;
        case 5:
            std::cout << "退出程序。" << std::endl;
            break;
        default:
            std::cout << "无效选择，请重新输入。" << std::endl;
        }
    } while (choice != 5);

    return 0;
}